package com.blog.message.api.config;

import cn.hutool.core.util.IdUtil;
import com.blog.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * <p>
 * 消息队列配置
 * </p>
 *
 * @author Valerie
 * @date 2023/5/27
 **/
@Slf4j
@Configuration
@SuppressWarnings("all")
public class RabbitMqConfig {

    @Resource
    private RedisService redisService;

    @Autowired
    private ConnectionFactory connectionFactory;



    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        return (correlationData, ack, cause) -> {
            if (ack){
                log.info("消息到达exchange！");
            }
            else {
                log.error("消息未到达exchange！");
            }
        };
    }

    @Bean
    public RabbitTemplate.ReturnsCallback returnsCallback() {
        return (returned) -> {
            // 处理消息退回的逻辑
            String messageId = returned.getMessage().getMessageProperties().getMessageId();

            rabbitTemplate().convertAndSend(returned.getExchange(), returned.getRoutingKey(), returned.getMessage());

            log.warn("消息重发！, 次数：{}", redisService.hasKey(messageId) ? redisService.get(messageId) : -1L);
        };
    }

    /** 自定义rabbitTemplate */
    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        rabbitTemplate.setConfirmCallback(confirmCallback());
        rabbitTemplate.setReturnsCallback(returnsCallback());
        rabbitTemplate.setBeforePublishPostProcessors(messageIdPostProcessor());
        rabbitTemplate.setMandatory(true);
        return rabbitTemplate;
    }

    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 服务启动时候开启自动启动
        rabbitAdmin.setAutoStartup(true);
        return rabbitAdmin;
    }


    @Bean
    public MessagePostProcessor messageIdPostProcessor() {
        return new MessageIdPostProcessor();
    }

    private static class MessageIdPostProcessor implements MessagePostProcessor {

        @Override
        public Message postProcessMessage(Message message) {
            // 生成消息的唯一标识符
            String messageId = IdUtil.getSnowflakeNextIdStr();
            // 设置消息的 messageId 属性
            message.getMessageProperties().setMessageId(messageId);
            return message;
        }
    }


}
